package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("CrawlerRestController")
public class CrawlerRestController extends CmiEmaController {

	/**
	 * Create a new Crawler entity
	 * 
	 */
	@RequestMapping(value = "/newCrawler", method = RequestMethod.POST)
	@ResponseBody
	public Object newCrawler(@RequestBody Crawler crawler) {
		crawlerService.saveCrawler(crawler);
		return JSONObject.parse(cmiPsonService.toJsonString(crawlerDAO.findCrawlerByPrimaryKey(crawler.getId()), 2));
	}

	@RequestMapping(value = "/restNewCrawler", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewCrawler(@RequestBody String crawlerJson) {
		Crawler crawler = new Gson().fromJson(crawlerJson, Crawler.class);
		appendReferences(crawler);
		crawlerService.saveCrawler(crawler);
		return JSONObject.parse(cmiPsonService.toJsonString(crawlerDAO.findCrawlerByPrimaryKey(crawler.getId()), 2));
	}

	@RequestMapping(value = "/saveCrawler", method = RequestMethod.PUT)
	@ResponseBody
	public Crawler saveCrawler(@RequestBody Crawler crawler) {
		crawlerService.saveCrawler(crawler);
		return crawlerDAO.findCrawlerByPrimaryKey(crawler.getId());
	}

	@RequestMapping(value = "/restSaveCrawler", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveCrawler(@RequestBody String crawlerJson) {
		Crawler crawler = new Gson().fromJson(crawlerJson, Crawler.class);
		appendReferences(crawler);
		CmiPsonService cmiPsonService = new CmiPsonService();
		crawlerService.saveCrawler(crawler);
		return JSONObject.parse(cmiPsonService.toJsonString(crawlerDAO.findCrawlerByPrimaryKey(crawler.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteCrawler/{crawlerId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteCrawler(@PathVariable Integer crawlerId) {
		Crawler crawler = crawlerDAO.findCrawlerByPrimaryKey(crawlerId);
		crawlerService.deleteCrawler(crawler);
	}

	@RequestMapping(value = "/restConfirmDeleteCrawlers")
	@ResponseBody
	public Object restConfirmDeleteCrawlers(@RequestBody Set<Integer> deleteCrawlersIds) {
		Set<Crawler> deleteCrawlers = crawlerDAO.findCrawlersByIds(deleteCrawlersIds);
		Set<Crawler> referencedCrawlers = crawlerService.loadReferenceCrawlers(deleteCrawlers);
		deleteCrawlers.removeAll(referencedCrawlers);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedCrawlers);
		jsonObject.put("deleteEntitys", deleteCrawlers);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteCrawlers")
	@ResponseBody
	public Object restDeleteCrawlers(@RequestBody Set<Crawler> deleteCrawlers) {
		Iterator<Crawler> iterator = deleteCrawlers.iterator();
		while (iterator.hasNext()) {
			Crawler currentCrawler = iterator.next();
			crawlerService.deleteCrawler(currentCrawler);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listCrawlers");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadCrawler/{crawlerId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawler(@PathVariable Integer crawlerId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(crawlerDAO.findCrawlerByPrimaryKey(crawlerId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadCrawlerCrawlerpictures/{crawlerId}/crawlerpictures/{relatedcrawlerpictureId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerCrawlerpictures(@PathVariable Integer crawlerId,
			@PathVariable Integer relatedcrawlerpictureId, @RequestBody CmiPagination cmiPagination) {
		Crawlerpicture crawlerpicture = crawlerpictureDAO.findCrawlerpictureByPrimaryKey(relatedcrawlerpictureId, -1,
				-1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(crawlerpicture, 2, cmiPagination));
	}

	public void appendReferences(Crawler crawler) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Crawlerpicture> crawlerpicturesForCrawler = new HashSet<>();
		for (Crawlerpicture crawlerpicture_Crawler : crawler.getCrawlerpicturesForCrawler()) {
			crawlerpicturesForCrawler
					.add(crawlerpictureService.findCrawlerpictureByPrimaryKey(crawlerpicture_Crawler.getId()));
		}
		crawler.setCrawlerpicturesForCrawler(crawlerpicturesForCrawler);
	}

	@RequestMapping(value = "/restGetCrawlerCrawlerpictures/{crawlerId}/crawlerpictures", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetCrawlerCrawlerpictures(@PathVariable Integer crawlerId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				crawlerDAO.findCrawlerByPrimaryKey(crawlerId).getCrawlerpicturesForCrawler(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListCrawlers", method = RequestMethod.GET)
	@ResponseBody
	public Object restListCrawlers() {
		return JSONObject.parse(cmiPsonService.toJsonString(crawlerService.loadCrawlers(), 2));
	}

	@RequestMapping(value = "/restListCrawlersPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListCrawlersPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = crawlerPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Crawler> crawlers = crawlerDAO.findAllCrawlers(startResult, cmiPagination.getPaginationSize());
		String crawlerString = cmiPsonService.toPsonString(crawlers, 2, cmiPagination);

		return JSONObject.parse(crawlerString);
	}

	@RequestMapping("/crawlerSelectBox")
	@ResponseBody
	public JSONObject crawlerSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Crawlerpicture":
				entitySet = crawlerpictureService.loadCrawlerpicturesByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Crawlerpicture":
				entitySet = crawlerpictureDAO.findAllCrawlerpictures((pageNumber - 1) * paginationSize, paginationSize);
				count = crawlerpictureService.countCrawlerpictures();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Crawlerpicture":
				entitySet = crawlerpictureDAO.findCrawlerpictureByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = crawlerpictureService.countCrawlerpicturesByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
